﻿/**********************************************************************
/// <summary>
// Name of File     :   ListUsers.cs
// Author           :   Parminder Singh
// Create date      :   17th Sep 2011
/// </summary>
************************************************************************/
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Crystal.Common.Model;
using CrystalAdmin.Presenter;
using System.Drawing;
using System.IO;
using Infragistics.Win.UltraWinGrid;
using Crystal.CLL;
using Crystal.CustomControls;
using System.ComponentModel;
namespace CrystalAdmin.View
{
    public partial class ListUsers : BaseForm, IListsUserView
    {
        #region Fields
        private IListUsersPresenter ListUsersPresenter;
        private USR_Users user;
        public event VoidEventHandler FindUserSearchResults;
        public event VoidEventHandler DeleteUser;
        public event SearchResultsEventHandler Searchusers;
        public event ExportToExcelEventHandler ExportToExcel;
        #endregion

        #region Properties

        public USR_Users CurrentUser
        {
            get { return (grdUsers.ActiveRow.ListObject) as USR_Users; }
            set
            {
                user = value;
            }
        }

        #endregion

        #region Constructors

        public ListUsers()
        {
            InitializeComponent();
            ListUsersPresenter = new ListUsersPresenter(this);
            //Load += ListUsers_Load;
            //rdAll.Checked = true;
        }

        #endregion

        #region Events

        #region Form Events

        private void ListUsers_Load(object sender, EventArgs e)
        {
            try
            {
                SetControlProperties();
                SetDefaulSearchText();
                rdAll.Checked = true;
                Application.DoEvents();
                FindUserSearchResults();
                ChangeColumnHeader();
            }
            catch (Exception ex)
            {
                this.LogErrorToDatabase(ex);
            }
        }

        private void ListUsers_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Escape)
                {
                    if (txtSearchUser.Focused)
                    { btnAddNewUser.Focus(); }
                    //else if (this.Focused)
                    //{ this.Close(); }
                }
                if (e.KeyCode == Keys.Enter)
                {
                    if (txtSearchUser.Focused)
                    {
                        rdSearchResult.Checked = true;
                        if (string.IsNullOrEmpty(txtSearchUser.Text.Trim()))
                        {
                            rdAll.Checked = true;
                        }
                        Searchusers(txtSearchUser.Text.Trim());
                    }

                }
            }
            catch (Exception ex)
            {
                this.LogErrorToDatabase(ex);
            }
        }

        public void ListUsers_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.FindUserSearchResults -= this.ListUsersPresenter.view_GetUsersList;
            this.DeleteUser -= this.ListUsersPresenter.view_DeleteUser;
            this.Searchusers -= this.ListUsersPresenter.view_FindUserBySearchResults;
            this.ExportToExcel -= this.ListUsersPresenter.view_ExportToExcel;
        }

        #endregion

        #region Grid Events

        private void grdUsers_InitializeRow(object sender, InitializeRowEventArgs e)
        {
            if (e.Row.Cells["UserStatus"].Value.ToString() == UserStatus.EXEMP.ToString())
            {
                int[] Values = new int[3];
                if (CommonCustomControls.IsValidString(StyleManager.GetStyle("EXEMPForeColor"), ref Values))
                {
                    e.Row.Appearance.ForeColor = Color.FromArgb(Values[0], Values[1], Values[2]);
                    //  e.Row.Appearance.BackColor= Color.Gray;
                }
            }
        }

        private void grdUsers_AfterSelectChange(object sender, AfterSelectChangeEventArgs e)
        {
            if (grdUsers.Selected.Rows.Count > 1)
            {
                EnableEditDeleteButton(false);
            }
            else
            {
                EnableEditDeleteButton(true);
            }
        }

        private void grdUsers_Click(object sender, EventArgs e)
        {
            if (grdUsers.Selected.Rows.Count > 1)
            {
                EnableEditDeleteButton(false);
            }
        }

        private void grdUsers_BeforeEnterEditMode(object sender, System.ComponentModel.CancelEventArgs e)
        {
            grdUsers.ActiveRow.Activation = Activation.ActivateOnly;
        }

        private void grdUsers_DoubleClickRow(object sender, DoubleClickRowEventArgs e)
        {
            ShowAddEditUser(ViewMode.EditMode);
        }

        #endregion

        #region Button Events

        private void btnDelete_Click(object sender, EventArgs e)
        {
            DialogResult diaresult;
            try
            {
                if (DeleteUser == null)
                {
                    diaresult = CYMessageBox.Show(MessageManager.GetMessage("SELECTUSER"), "Exit", CYMessageBox.CustomButtons.OK, CYMessageBox.CYIcon.Warning);
                }
                diaresult = CYMessageBox.Show(MessageManager.GetMessage("DELETEUSER", grdUsers.ActiveRow.Cells["UserName"].Value), "Exit", CYMessageBox.CustomButtons.YesNo, CYMessageBox.CYIcon.Warning);
                if (diaresult == DialogResult.Yes)
                {
                    if (DeleteUser != null)
                    {
                        DeleteUser();
                        diaresult = CYMessageBox.Show(MessageManager.GetMessage("USERDELETED"), "Exit", CYMessageBox.CustomButtons.OK, CYMessageBox.CYIcon.Warning);
                        FindUserSearchResults();
                    }
                }
            }
            catch (Exception ex)
            {
                this.LogErrorToDatabase(ex);
            }
        }

        private void btnAddNewUser_Click(object sender, EventArgs e)
        {
            ShowAddEditUser(ViewMode.AddMode);
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            ShowAddEditUser(ViewMode.EditMode);

        }

        private void btnExportToExcel_Click(object sender, EventArgs e)
        {
            try
            {
                ExportToExcel(grdUsers);
            }
            catch (Exception ex)
            {
                this.LogErrorToDatabase(ex);
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnAddNewUser_MouseHover(object sender, EventArgs e)
        {
            GetTooltip(btnAddNewUser, "ADDNEWUSER");
        }

        private void btnExportToExcel_MouseHover(object sender, EventArgs e)
        {
            GetTooltip(btnExportToExcel, "EXPORTTOEXCEL");
        }

        #endregion

        #region Text Box Events

        private void txtSearchUser_TextChanged(object sender, EventArgs e)
        {
            //if (string.IsNullOrEmpty(txtSearchUser.Text.Trim()))
            //{
            //    rdAll.Checked = true;
            //    FindUserSearchResults();
            //}
            //else
            //{
            //if (!rdSearchResult.Checked)
            //    rdSearchResult.Checked = true;
            //}
        }

        private void txtSearchUser_Leave(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtSearchUser.Text.Trim()))
            {
                SetDefaulSearchText();
                rdAll.Checked = true;
            }
        }

        private void txtSearchUser_MouseClick(object sender, MouseEventArgs e)
        {
            //rdSearchResult.Checked = true;
            if (MessageManager.GetMessage("DEFAULTSEARCHTEXT") == txtSearchUser.Text)
            {
                txtSearchUser.Text = string.Empty;
            }
        }

        #endregion

        #region Radio Button Events

        private void rdAll_Click(object sender, EventArgs e)
        {
            try
            {
                if (!rdAll.Checked)
                {
                    FindUserSearchResults();
                }
                else
                {
                    txtSearchUser.Text = MessageManager.GetMessage("DEFAULTSEARCHTEXT");
                    rdAll.Checked = true;
                    FindUserSearchResults();
                }
            }
            catch (Exception ex)
            {
                this.LogErrorToDatabase(ex);
            }
        }

        #endregion

        #endregion

        #region Methods

        public void GetAllUsersBySearchText()
        {
            FindUserSearchResults();
        }

        private void SetControlProperties()
        {
            this.Text = TitleManager.GetTitle("UserManagement");
            int[] Values = new int[3];
            if (CommonCustomControls.IsValidString(StyleManager.GetStyle("EXEMPForeColor"), ref Values))
            {
                lblExEmployees.ForeColor = Color.FromArgb(Values[0], Values[1], Values[2]);
                //  e.Row.Appearance.BackColor= Color.Gray;
            }
           
        }

        public void GetUsersList(BindingList<USR_Users> users)
        {
            grdUsers.DataSource = users;
            grdUsers.Rows.Refresh(RefreshRow.ReloadData);

            //grdUsers.UpdateMode = UpdateMode.OnUpdate;
            //grdUsers.DataSource = users;
            //grdUsers.DataBind();
            //grdUsers.Rows.Refresh(RefreshRow.ReloadData);
            ////grdUsers.Refresh();
            ////grdUsers.
        }

        public void RefreshUsersList()
        {
            //grdUsers.DataSource = users;
            grdUsers.Rows.Refresh(RefreshRow.RefreshDisplay);

            //grdUsers.UpdateMode = UpdateMode.OnUpdate;
            //grdUsers.DataSource = users;
            //grdUsers.DataBind();
            //grdUsers.Rows.Refresh(RefreshRow.ReloadData);
            ////grdUsers.Refresh();
            ////grdUsers.
        }

        private void GetTooltip(Control control, string tooltip)
        {
            toolTip1.SetToolTip(control, ToolTipManager.GetToolTip(tooltip));
        }

        private void ShowAddEditUser(ViewMode viewMode)
        {
            //AddEditUser lfrmAddEditUser = new AddEditUser(CurrentUser);
            //lfrmAddEditUser.Show();
            //return;
            string titlewithName = string.Empty;
            AddEditUser frmAddEditUser = new AddEditUser(viewMode==ViewMode.EditMode ? CurrentUser : null);
            frmAddEditUser.viewMode = viewMode;
            try
            {
                titlewithName = TitleManager.GetTitle(viewMode.ToString());
                if (viewMode==ViewMode.EditMode)
                {
                    titlewithName += CurrentUser.FirstName + " " + CurrentUser.LastName;
                }
                frmAddEditUser.Text = titlewithName;
                //frmAddEditUser.Show();
                if (CommonCLL.FocusOnExistingInstanceByText(frmAddEditUser.Text))
                {
                    frmAddEditUser.Show();
                    frmAddEditUser.BringToFront();
                }
                else
                {
                    //if (frmAddEditUser.WindowState == FormWindowState.Minimized)
                    //    frmAddEditUser.WindowState = FormWindowState.Normal;
                    ////frmAddEditUser.Select();
                    //frmAddEditUser.Activate();
                    frmAddEditUser.Focus();
                   
                }

            }
            catch (Exception ex)
            {
                this.LogErrorToDatabase(ex);
            }
            finally
            {
                ///frmAddEditUser.Dispose();
            }
        }

        public void SetFocus()
        {
            if (this.WindowState == FormWindowState.Minimized)
                this.WindowState = FormWindowState.Normal;
            this.Focus();
            this.BringToFront();
        }

        private void EnableEditDeleteButton(bool isEnable)
        {
            btnEdit.Enabled = isEnable;
            btnDelete.Enabled = isEnable;
        }

        public void ChangeColumnHeader()
        {
            grdUsers.Rows.Band.Columns["UserID"].Hidden = true;
            grdUsers.Rows.Band.Columns["UserStatus"].Hidden = true;
            grdUsers.Rows.Band.Columns["Password"].Hidden = true;
            grdUsers.Rows.Band.Columns["IsLoggedIn"].Hidden = true;
            grdUsers.Rows.Band.Columns["DateCreated"].Hidden = true;

            grdUsers.Rows.Band.Columns["FirstName"].Header.Caption = "First Name";
            grdUsers.Rows.Band.Columns["LastName"].Header.Caption = "Last Name";
            grdUsers.Rows.Band.Columns["UserName"].Header.Caption = "User Name";
            grdUsers.Rows.Band.Columns["EMailAddress"].Header.Caption = "Email Address";
        }

        public void SetDefaulSearchText()
        {
            txtSearchUser.Text = MessageManager.GetMessage("DEFAULTSEARCHTEXT");
        }
        #endregion  
    }
}
